﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using CY_MVC.ViewTemplate;

namespace CY_MVC.Core
{
    public static class ViewTemplateContext
    {
        private static readonly object Lockobject = new object();
        private static readonly IDictionary<string, BaseViewTemplate> Views = new Dictionary<string, BaseViewTemplate>();

        private static Type ViewTemplateType;

        private static BaseViewTemplate ViewTemplate
        {
            get
            {
                if (ViewTemplateType == null)
                {
                    if (string.IsNullOrEmpty(StaticConfig.ViewTemplateName))
                    {
                        ViewTemplateType = typeof (ViewTemplate.Default.ViewTemplate);
                    }
                    else
                    {
                        ViewTemplateType = Assembly.Load(StaticConfig.ViewTemplateName)
                                                   .GetType(StaticConfig.ViewTemplateName + ".ViewTemplate");
                    }
                    if (ViewTemplateType == null)
                        throw new Exception(StaticConfig.ViewTemplateName + "模版引擎不存在");
                }
                return (BaseViewTemplate) Activator.CreateInstance(ViewTemplateType);
            }
        }

        public static BaseViewTemplate GetView(HttpHandlers.BaseController p_BaseController)
        {
            return GetView(StaticConfig.TemplatePath + p_BaseController.GetType().FullName.Replace(StaticConfig.ControllerName + ".", string.Empty).Replace(".", "\\").ToLowerInvariant());
        }

        public static BaseViewTemplate GetView(string p_TemplateName)
        {
            if (!Views.ContainsKey(p_TemplateName))
            {
                lock (Lockobject)
                {
                    if (!Views.ContainsKey(p_TemplateName))
                    {
                        var MyViewTemplate = ViewTemplate;
                        if (File.Exists(StaticConfig.RootPath + p_TemplateName.TrimStart('/') + MyViewTemplate.Extension))
                        {
                            MyViewTemplate.SetTemplateFile(p_TemplateName + MyViewTemplate.Extension);
                            Views[p_TemplateName] = MyViewTemplate;
                        }
                        else if (File.Exists(StaticConfig.RootPath + p_TemplateName.TrimStart('/')))
                        {
                            MyViewTemplate.SetTemplateFile(p_TemplateName);
                            Views[p_TemplateName] = MyViewTemplate;
                        }
                        else
                        {
                            throw new Exception(p_TemplateName + "模版文件不存在");
                        }
                    }
                }
            }
            return Views[p_TemplateName];
        }
    }
}
